<script setup lang="tsx">
/**
 * @name MenuManagement
 * @description 菜单管理
 */
import {
  Delete,
  Edit,
  Plus,
  Warning,
} from '@element-plus/icons-vue'
import type { Action } from 'element-plus'
import { ElSwitch, ElTag } from 'element-plus'
import { FormModal } from './components'
import { defaultFormData } from './index'
import type {
  MenuInfo,
  MenuSaveOrUpdateParams,
  TableColumn,
} from '@/types'
import { sysMenuApi } from '@/api'
// ------------------use------------------
// #region
const { $confirm, $message, $power } = useCurrentInstance()
const { withLoading, loading } = useDefineLoading()
const [tableData, setTableData] = useState<MenuInfo[]>([])
const [formData, setFormData] = useState<
  Partial<MenuSaveOrUpdateParams>
>({
  ...defaultFormData,
})
const [formModalTitle, setFormModalTitle]
  = useState<string>('')
// #endregion
// ------------------静态变量------------------
// #region
const columns: TableColumn<MenuInfo>[] = [
  { key: uuid(), prop: 'id', width: '120', label: 'ID' },
  {
    key: uuid(),
    label: '菜单名称',
    prop: 'menuName',
  },
  {
    key: uuid(),
    label: '菜单标题',
    prop: 'menuTitle',
    header: () => {
      return (
        <span class="align-center flex justify-center">
          菜单标题
          <el-tooltip
            content="页签显示标题，默认为菜单名称"
            placement="top"
          >
            <el-icon class="c-pointer margin-left-xs text-orange">
              <Warning />
            </el-icon>
          </el-tooltip>
        </span>
      )
    },
    render: ({ row }) => {
      return row.menuTitle || row.menuName
    },
  },
  {
    key: uuid(),
    label: '菜单排序',
    prop: 'xh',
    hidden: true,
    header: () => {
      return (
        <span class="align-center flex justify-center">
          菜单排序
          <el-tooltip
            content="数值越小排序等级越高"
            placement="top"
          >
            <el-icon class="c-pointer margin-left-xs text-orange">
              <Warning />
            </el-icon>
          </el-tooltip>
        </span>
      )
    },
    render: ({ row }) => {
      return row.xh
    },
  },
  {
    key: uuid(),
    label: '菜单标识',
    prop: 'identifying',
  },
  {
    key: uuid(),
    label: '菜单路径',
    prop: 'menuAddress',
  },
  {
    key: uuid(),
    label: '重定向',
    hidden: true,
    header: () => {
      return (
        <span class="align-center flex justify-center">
          重定向
          <el-tooltip
            content="用于跳转到第三方平台"
            placement="top"
          >
            <el-icon class="c-pointer margin-left-xs text-orange">
              <Warning />
            </el-icon>
          </el-tooltip>
        </span>
      )
    },
    prop: 'redirect',
  },
  {
    key: uuid(),
    label: '菜单类型',
    render({ row }) {
      if (!row.menuType)
        return ''
      if (row.menuType === 1) {
        return h(ElTag, null, {
          default: () => '目录',
        })
      }
      else if (row.menuType === 2) {
        return h(
          ElTag,
          {
            type: 'success',
          },
          {
            default: () => '页面',
          },
        )
      }
      else if (row.menuType === 3) {
        return h(
          ElTag,
          {
            type: 'info',
          },
          {
            default: () => '按钮',
          },
        )
      }
      else {
        return h(
          ElTag,
          {
            type: 'danger',
          },
          {
            default: () => '驾驶舱',
          },
        )
      }
    },
  },
  // {
  //   key: uuid(),
  //   label: '启用',
  //   header: () => {
  //     return (
  //       <span class="align-center flex justify-center">
  //         启用
  //         <el-tooltip
  //           content="页面不会注册"
  //           placement="top"
  //         >
  //           <el-icon class="c-pointer margin-left-xs text-orange">
  //             <Warning />
  //           </el-icon>
  //         </el-tooltip>
  //       </span>
  //     )
  //   },
  //   render({ row }) {
  //     return h(ElSwitch, {
  //       modelValue: row.menuEnable,
  //       activeValue: 1,
  //       inactiveValue: 0,
  //       disabled: !$power('edit'),
  //       onclick: () => {
  //         handlerSwitchStatus(row, 'menuEnable')
  //       },
  //     })
  //   },
  // },
  {
    key: uuid(),
    label: '隐藏',
    header: () => {
      return (
        <span class="align-center flex justify-center">
          隐藏
          <el-tooltip
            content="仅在左侧菜单项隐藏"
            placement="top"
          >
            <el-icon class="c-pointer margin-left-xs text-orange">
              <Warning />
            </el-icon>
          </el-tooltip>
        </span>
      )
    },
    render({ row }) {
      return h(ElSwitch, {
        modelValue: row.isHidden,
        activeValue: 1,
        inactiveValue: 0,
        disabled: !$power('edit'),
        onclick: () => {
          handlerSwitchStatus(row, 'isHidden')
        },
      })
    },
  },
  {
    key: uuid(),
    label: '全屏',
    hidden: true,
    render({ row }) {
      return h(ElSwitch, {
        modelValue: row.isFullscreen,
        activeValue: 1,
        inactiveValue: 0,
        disabled: !$power('edit'),
        onclick: () => {
          handlerSwitchStatus(row, 'isFullscreen')
        },
      })
    },
  },
  {
    key: uuid(),
    label: '菜单图标',
    hidden: true,
    prop: 'menuIcon',
  },
  {
    key: uuid(),
    label: '上级菜单ID',
    hidden: true,
    prop: 'parentId',
  },
]
// #endregion
// ------------------动态变量------------------
// #region

// #endregion
// ------------------ref-----------
// #region
const modalRef = ref<InstanceType<typeof FormModal>>()
// #endregion
// ------------------reactive------
// #region

// #endregion
// ------------------computed------
// #region
// #endregion
// ------------------生命周期------------------
// #region
onMounted(() => {
  getTableData()
})
// #endregion
// ------------------内置方法---------------------
// #region

// #endregion
// ------------------方法---------------------
// #region
async function deleteData(id: number) {
  const res: Action = await $confirm(
    '该操作将永久删除该数据，确定删除？',
    '警告',
    {
      type: 'warning',
    },
  ).catch(e => e)

  if (res !== 'confirm')
    return
  const { code } = await sysMenuApi.deleteById(id)
  if (code !== 200)
    return
  getTableData()
}
async function showEditDialog(row: any) {
  modalRef.value?.open()
  await nextTick()
  setFormModalTitle('编辑')
  setFormData({ ...defaultFormData, ...row })
}
async function showAddDialog() {
  modalRef.value?.open()
  await nextTick()
  setFormModalTitle('新增')
  setFormData({ ...defaultFormData })
}
async function getTableData() {
  const { data: res } = await withLoading(
    sysMenuApi.queryTreeList,
  )()
  setTableData(res)
}
async function addOrUpdateData(row: Partial<MenuSaveOrUpdateParams>) {
  const params = { ...row }
  // if (params.menuType !== 3 && !params.parentId) {
  if (!params.parentId) {
    params.parentId = 0
  }
  removeUnnecessaryParams(params)
  const { code } = await sysMenuApi.saveOrUpdate(params)
  if (code !== 200)
    return
  getTableData()
  modalRef.value?.close()
  $message.success('保存成功！')
}
function handlerSwitchStatus(row: Partial<MenuSaveOrUpdateParams>, str: string) {
  const params: Partial<MenuSaveOrUpdateParams> = {
    parentId: row.parentId,
    id: row.id,
    [str]: +!(row as any)[str],
  }
  withLoading(addOrUpdateData)(params)
}
function success() {
  getTableData()
  modalRef.value?.close()
  $message.success('保存成功！')
}
// #endregion
</script>

<template>
  <div
    class="padding-sm flex-direction flex align-end container"
  >
    <view-table
      :loading="loading"
      :columns="columns"
      :data="tableData"
      :show-download="false"
    >
      <template #actions>
        <el-button
          :disabled="!$power('add')"
          type="primary"
          :icon="Plus"
          @click="showAddDialog"
        >
          新增
        </el-button>
      </template>
      <template #operate="{ row }">
        <TdButton
          title="编辑"
          :icon="Edit"
          type="primary"
          @click="showEditDialog(row)"
        />
        <TdButton
          title="删除"
          :icon="Delete"
          type="danger"
          @click="deleteData(row.id)"
        />
      </template>
    </view-table>

    <FormModal
      ref="modalRef"
      v-model:data="formData"
      :menu-data="tableData"
      :title="formModalTitle"
      @save-success="success"
    />
  </div>
</template>

<style lang="scss" scoped>
//------------------组件样式------------------
//-------------样式穿透-------------
</style>
